import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '@common/database/entity/user.entity';
import { MiniProgramRegisterDto } from './dto/mini-program-login.dto';
import { ApiFail } from '@common/utils';
import { SysConfig } from '@common/database/entity/sys_config.entity';
import { ChargeRecord } from '@common/database/entity/charge_record.entity';
import { AmountChangeTypeEnum } from '@common/enum/user.enum';

@Injectable()
export class UserService {
  constructor(
    @Inject('USER_REPOSITORY')
    public readonly repo: Repository<User>,
    @Inject('CHARGE_RECORD_GREPOSITORY')
    public readonly chargeRecordRepo: Repository<ChargeRecord>,
  ) {}

  //获取会员id
  async getUserInfo(where: any) {
    const user = await this.repo.findOne({
      where: where,
    }); /*  */
    if (!user) {
      throw new ApiFail(101, '用户名不存在');
    }

    if (!user.status) {
      throw new ApiFail(103, '用户已被禁用');
    }
    console.log(user);

    return user;
  }
  //获取会员id
  async getUser(opendId: string) {
    const user = await this.repo
      .createQueryBuilder('user')
      // "id,mobile,userName,weixin_openId,nickName,avatar,is_new"
      .select([
        'user.id',
        'user.weixin_openId',
        'user.nickName',
        'user.avatar',
        'user.is_new',
      ]) // 查询 id 和 username
      .where('user.weixin_openId=:id', { id: opendId })
      .getOne();
    console.log(user);
    return user;
  }

  async update(where, user) {
    return await this.repo.update(where, user);
  }
  async findVip(where) {
    return await this.chargeRecordRepo.findOne({ where });
  }
  async isValidUser(where) {
    return await this.repo.findOne({ where });
  }
  async updateRecord(where, data) {
    return await this.chargeRecordRepo.update(where, data);
  }

  async changeUserAmount(userId: string, changeAmount: number) {
    const user = await this.repo.findOne({ where: { id: userId } });
    if (!user) {
      throw new ApiFail(500,'user not found');
    }
    console.log(user.amount);
    console.log(changeAmount);
    console.log(user.amount - changeAmount);
    const num = user.amount - changeAmount;
    if (num < 0) {
      throw new ApiFail(500,'余额不足了,请充值');
    }

    // // 写入变更记录
    // await this.chargeRecordRepo.save({
    //   userId: userId,
    //   changeAmount: changeAmount,
    //   changeType: AmountChangeTypeEnum.Consume,
    //   describe: '',
    // });

    // 更新余额
    await this.repo
      .createQueryBuilder()
      .update(User)
      .set({ amount: num })
      .where('id = :id', { id: userId })
      .execute()
    return num;
  }


  async getImgUrl(req: any) {
    const user = await this.repo
      .createQueryBuilder('user')
      // "id,mobile,userName,weixin_openId,nickName,avatar,is_new"
      .select([
        'user.avatar',
      ]) // 查询 id 和 username
      .where('user.id=:id', { id: req.id })
      .getOne();
    console.log(user);
    if(user){
      return user.avatar;
    }
    return "https://minio.frp.hosea123.com/public/CROP_20240118123656821.jpg"
  }
}
